package org.apogee.mil.server.superuser;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

import org.apache.log4j.Logger;
import org.apogee.mil.client.services.superuser.SuperUserService;
import org.apogee.mil.server.database.DatabaseDriver;
import org.apogee.mil.server.database.helper.DatabaseQueries;
import org.apogee.mil.shared.Constants.DisplayFormat;
import org.apogee.mil.shared.Constants.UserLookupFields;

import com.extjs.gxt.ui.client.data.BaseModel;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class SuperUserServiceImpl extends RemoteServiceServlet implements SuperUserService {

	private static Logger logger = Logger.getLogger(SuperUserServiceImpl.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private DatabaseDriver db;
	
	@Override
	public ArrayList<BaseModel> executeQuery(String query) throws Exception {
		logger.info("Super User Mode");
		
		ArrayList<BaseModel> results = new ArrayList<BaseModel>();
		
		ResultSet set = db.executeQuery(query);
		
		while (set.next()) {
			
			BaseModel bm = new BaseModel();
			
			ResultSetMetaData rsmd = set.getMetaData();
			
			for (int index = 1; index < rsmd.getColumnCount(); index++) {
				String columnName = rsmd.getColumnName(index);
				String columnValue = set.getString(index);
				bm.set(columnName, columnValue);
			}
			
			results.add(bm);
		}
		
		return results;
	}

	@Override
	public boolean initialize() {
		db = new DatabaseDriver();
		return db.initialize();
	}

	@Override
	public boolean close() {
		return db.close();
	}

	@Override
	public ArrayList<BaseModel> getAllScores() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ArrayList<BaseModel> getAllUsers() throws Exception {
		String stmt = DatabaseQueries.GET_ALL_USERS;


		ArrayList<BaseModel> users = new ArrayList<BaseModel>();

		ResultSet set = db.executeQuery(stmt);

		try {
			while (set.next()) {
				BaseModel bm = new BaseModel();

				String userId = set.getString(UserLookupFields.USER_ID);
				String fName = set.getString(UserLookupFields.FIRST_NAME);
				String lName = set.getString(UserLookupFields.LAST_NAME);

				bm.set(DisplayFormat.USER_FMT, userId + " - " + fName + " " + lName);
				users.add(bm);
			}
		} catch (SQLException e) {
			logger.error(e);
			throw e;
		}

		return users;
	}

}
